<template>
  <div class="fileManagerPage">
    <div class="fileManagerPage_main" :style="{transform:(transFlag==0 ?'rotateY(180deg)':'')}">
      <div class="fileManagerPage_main_search">
        <span style="flex:1">
          <span>选择日期:</span>
          <span class="dataPicker">
            <el-date-picker
              v-model="pickerValue"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
              @change="changePickerValue"
            />
          </span>
        </span>
      </div>
      <div class="fileManagerPage_main_title">
        <div style="flex:1">
          <vxe-input v-model="filterName" type="search" placeholder="试试全表搜索名称" @keyup="searchEvent" />
        </div>
        <div class="fileManagerPage_main_title_text">文件列表</div>
        <div class="buttonType" style="flex:1;text-align:right">
          <el-button type="primary" size="small" @click="showDialogFile">上传文件</el-button>
        </div>
      </div>
      <div class="fileManagerPage_main_table">
        <vxe-table
          ref="fileTable"
          v-loading="tableLoading"
          :data="tableData"
          border
          stripe
          resizable
          highlight-hover-row
          highlight-current-row
          show-overflow
          :height="tableHeight"
          :header-cell-style="headerCellStyle"
          :cell-style="cellStyle"
        >
          <vxe-table-column
            :min-width="800"
            field="originName"
            title="名称"
          >
            <template slot-scope="scope">
              <svg-icon icon-class="file" />
              <span v-if="scope.row.getWay===&quot;remote&quot;" style="color:red">(来自南威)</span>
              <span v-if="scope.row.getWay===&quot;local&quot;" style="color:green">(来自资金监管)</span>
              <span v-if="scope.row.getWay===&quot;local&quot; && scope.row.userId+''===userId">(本人上传)</span>
              <span>{{ scope.row.originName }}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column
            :min-width="50"
            field="uploadTime"
            title="日期"
          />
          <vxe-table-column width="150" title="操作" field="do" fixed="right">
            <template slot-scope="scope" style="text-align:center">
              <div style="text-align: center;">
                <span
                  v-if="scope.row.getWay===&quot;local&quot; && scope.row.userId+''===userId"
                  style="margin-right:10px"
                >
                  <el-popconfirm
                    title="确定要删除文件吗？"
                    @onConfirm="deleteFile(scope.row)"
                  >
                    <el-button slot="reference" type="text" size="medium" class="deleteSpecial">删除</el-button>
                  </el-popconfirm>
                </span>
                <el-button type="text" size="medium" @click="lookTable(scope.row)">查看</el-button>
              </div>
            </template>
          </vxe-table-column>
          <template #empty>
            <span style="color: red;">
              <img style="height:150px" src="../../assets/images/monthReport/noReport.png">
              <div>暂无文件数据</div>
            </span>
          </template>
        </vxe-table>
      </div>
      <!-- 分页 -->
      <div class="commonTable_pagination">
        <div class="commonTable_pagination_right">
          <el-pagination
            background
            :current-page="pageIndex"
            :page-sizes="[50, 100, 150, 200]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="count"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <div class="fileManagerPage_main_dialog">
        <el-dialog
          v-dialogDrag
          title="文件上传"
          :visible.sync="dialogVisible"
          :width="width"
          :before-close="handelClose"
          :close-on-click-modal="false"
          append-to-body
        >
          <div class="dialogContent">
            <div class="dialogContent_left">
              <el-upload
                ref="upLoad"
                :auto-upload="false"
                class="upload-demo"
                :on-success="handleSuccess"
                :on-error="showFalse"
                :on-remove="handleRemove"
                :on-change="handleChange"
                :file-list="fileList"
                :action="upLoadUrl"
                :data="upLoadParam"
                :limit="1"
                :on-exceed="handleExceed"
                multiple
                drag
              >
                <div style="margin: 20px 0px;">
                  <svg-icon icon-class="fileIcon" />
                </div>
                <div>
                  <div class="el-upload__text">点击或将文件拖拽到这里上传 </div>
                  <div class="el-upload_type">支持扩展名：.rar .zip .doc .docx .pdf .jpg... </div>
                </div>
                <div slot="tip" class="el-upload__tip">只能上传一个文件</div>
              </el-upload>
              <div style="margin-top:15px">
                <div style="margin-bottom:10px">
                  <el-checkbox v-model="isTips">上传文件后通知他人</el-checkbox>
                </div>
                <div class="dialogContent_left_tips">
                  <div class="dialogContent_left_tips_title">
                    <div class="dialogContent_left_tips_title_left">已选中:{{ toData.length }}条</div>
                    <div class="dialogContent_left_tips_title_right">
                      <span>人员列表</span>
                      <span style="font-size:12px"><el-checkbox v-model="checked" @change="chooseCheck" />
                        全选
                      </span>
                    </div>
                  </div>
                  <div style="padding:8px 10px">
                    <el-input v-model="searchContent" style="width: 90%;" placeholder="关键词搜索">
                      <i slot="suffix" class="el-input__icon el-icon-search" />
                    </el-input>
                  </div>
                  <div class="dialogContent_left_treeContainer">
                    <el-tree
                      ref="tree"
                      :data="fromData"
                      show-checkbox
                      node-key="id"
                      highlight-current
                      :filter-node-method="filterNode"
                      :props="defaultProps"
                      @check-change="handledeptNodeClick"
                    />
                  </div>
                </div>
              </div>
            </div>
            <div class="dialogContent_right">
              <div v-if="fileList.length===0" class="dialogContent_right_bg" />
              <div
                v-else
                v-loading="previewLoading"
                style="height:100%"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgb(31 30 30 / 80%)"
              >
                <iframe frameborder="0" style="width:100%;border:none;height:calc(74vh)" :src="fileSrc" />
              </div>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="handelClose">取 消</el-button>
            <el-popconfirm
              title="你确定要上传该文件吗？"
              @onConfirm="makeSure"
              @onCancel="cancelPop"
            >
              <el-button slot="reference" type="primary" size="small">提 交</el-button>
            </el-popconfirm>
          </span>
        </el-dialog>
      </div>
    </div>
    <div class="fileManagerPage_file" :style="{transform:(transFlag==0 ?'rotateY(0deg)':'')}">
      <div class="fileManagerPage_file_main">
        <div class="fileManagerPage_file_main_title">
          <div class="fileManagerPage_file_main_title_text" @click="goBack">
            <svg-icon icon-class="back" />
            <span style="position: relative;top: -1px;"> 返回首页</span>
          </div>
          <div class="fileManagerPage_file_main_title_down" style="flex:1;text-align:right">
            <el-button type="primary" size="small" @click="downFile">下载文件</el-button>
          </div>
        </div>
        <div
          v-loading="isLoading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgb(31 30 30 / 80%)"
          class="fileManagerPage_file_main_content"
        >
          <div v-if="isLoading" class="filePreviewBg" />
          <iframe v-if="transFlag===0 && !isLoading" frameborder="0" style="height:calc(74vh);width:100%;border:none;" :src="fileSrc" />
        </div>

      </div>
    </div>
  </div>
</template>

<script >
import { getFileList, getUserList, sendMsg, removeFile, uploadFile, uploadNanWei } from '@/api/filePage/index';
import { getGlobal } from '@/utils/global';
// import Vue from 'vue';
export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      pickerValue: [],
      filterName: '',
      tableData: [],
      tableLoading: false,
      tableHeight: '',
      pageSize: 50,
      pageIndex: 1,
      dialogVisible: false,
      width: '850px',
      count: 0,
      userId: 0,
      transFlag: 1,
      fileSrc: '',
      isLoading: false,
      upLoadUrl: '',
      fileList: [],
      isTips: false,
      upLoadParam: {
        'type': localStorage.getItem('fileType'),
        'userId': localStorage.getItem('xcUserId'),
        'extraPath': ''
      },
      fromData: [],
      defaultProps: {
        children: 'children',
        label: 'lable'
      },
      toData: [],
      row: {},
      previewLoading: false,
      isUpload: true,
      searchContent: '',
      checked: false
    };
  },
  watch: {
    searchContent: {
      // 监听的对象
      deep: true, // 深度监听设置为 true
      handler: function(newV, oldV) {
        this.$refs.tree.filter(newV);
      }
    }
  },
  created() {
    const startDate = new Date().getFullYear() + '-' + ((new Date().getMonth() + 1) < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1) + '-' + '01';
    const end_date = new Date();
    const yy = end_date.getFullYear();
    const mm = end_date.getMonth() + 1;
    const end = new Date(yy, mm, 0).getDate();
    const endDate = new Date().getFullYear() + '-' + ((new Date().getMonth() + 1) < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1) + '-' + end;
    this.pickerValue = [startDate, endDate];
    this.userId = localStorage.getItem('xcUserId') + '';
    getGlobal().then((all) => {
      this.upLoadUrl = `${all.url}/file/upload`;
    });
    this.getDataSource();
  },
  // mounted() {
  //   this.tableHeight =
  //     window.innerHeight - this.$refs.fileTable.$el.offsetTop - 200;
  //   const _this = this;
  //   if (JSON.parse(localStorage.getItem('buttonType'))) {
  //     for (let i = 0; i < JSON.parse(localStorage.getItem('buttonType')).length; i++) {
  //       var MyComponent = Vue.extend({
  //         data() {
  //           return {
  //             a: JSON.parse(localStorage.getItem('buttonType'))[i].auth
  //           };
  //         },
  //         methods: {
  //           commonDo(item) {
  //             if (item.split(' ')[0] === 'upload') {
  //               _this.showDialogFile();
  //             } else if (item.split(' ')[0] === 'down') {
  //               _this.downFile();
  //             } else {
  //               this.$message.warning('该页面没有该按钮的功能');
  //             }
  //           }
  //         },
  //         template: `<span style='margin-right:10px'>
  //     <span v-for='item in a'>
  //       <el-button  type="text" @click='commonDo(item)'>{{item.split(' ')[1]}}</el-button>
  //     </span>
  //     </span>`
  //       });
  //       // 手动创建，手动挂载
  //       var component = new MyComponent().$mount();
  //       var dom = document.querySelector(JSON.parse(localStorage.getItem('buttonType'))[i].key);
  //       dom.appendChild(component.$el);
  //     }
  //   }
  // },
  methods: {
    cellStyle({ row, rowIndex, column }) {
      if (column.property === 'originName') {
        return {};
      } else {
        return {
          textAlign: 'center'
        };
      }
    },
    chooseCheck() { // el-tree全选事件
      if (this.checked) { // 全选
        this.$refs.tree.setCheckedNodes(this.fromData);
      } else { // 取消选中
        this.$refs.tree.setCheckedKeys([]);
      }
    },
    handledeptNodeClick() {
      // 只取底层
      this.toData = this.$refs.tree.getCheckedNodes(true);
    },
    filterNode(value, data) {
      // 后端传值错误，传了个lable,本来应该是label
      if (!value) {
        return true;
      } else {
        if (data.lable) {
          return data.lable.indexOf(value) !== -1;
        }
      }
    },
    deleteFile(row) {
      removeFile({
        id: row.id
      }).then(res => {
        if (res.success) {
          this.$message.success('删除文件成功');
          this.getDataSource();
        } else {
          this.$message.warning('删除文件失败');
        }
      });
    },
    // 发送消息
    sendMessage(file) {
      let receiverPhones = '';
      this.toData.map((item, index) => {
        receiverPhones += item.telephone + ',';
      });
      receiverPhones = receiverPhones.substr(0, receiverPhones.length - 1);
      sendMsg({
        'fileName': file.originName,
        'userName': localStorage.getItem('xcNickName'),
        'receiverPhones': receiverPhones
      }).then(res => {
        if (res.success) {
          this.$message.success('上传成功并通知人成功');
        } else {
          this.$message.warning('上传成功但通知失败');
        }
      });
    },
    // 确定
    makeSure() {
      if (this.fileList.length === 0) {
        this.$message.warning('系统监测到您还没上传文件!!!');
      } else {
        if (this.isTips) {
          if (this.toData.length === 0) {
            this.$message.warning('系统监测到你勾选了提示，但没有选择人');
          } else {
            this.$refs.upLoad.submit();
          }
        } else {
          if (this.toData.length !== 0) {
            this.$message.warning('系统监测到您选择了人,但是没有勾选提示');
          } else {
            this.$refs.upLoad.submit();
          }
        }
      }
    },
    cancelPop() {
      console.log('取消');
    },
    handleExceed(files, fileList) {
      this.$message.warning('当前限制只能上传一份文件');
    },
    handleSuccess(response) {
      if (response.success) {
        if (this.isTips) {
          this.sendMessage(response.data);
        } else {
          this.$message({
            message: '上传成功',
            type: 'success'
          });
        }
        setTimeout(() => {
          this.handelClose();
          this.getDataSource();
        }, 1000);
      } else {
        this.$message({
          message: response.msg,
          type: 'warning'
        });
      }
      setTimeout(() => {
        this.isUpload = true;
      }, 2000);
      this.fileList = [];
    },
    showFalse() {
      this.$message({
        message: '上传失败',
        type: 'warning'
      });
      this.dialogVisible = false;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      // 调用接口，进行预览，相当于是垃圾数据
      // // 创建FormData对象
      if (this.isUpload) {
        this.fileSrc = '';
        this.previewLoading = true;
        const param = new FormData();
        // 将得到的文件流添加到FormData对象
        param.append('file', file.raw);
        param.append('type', '1006');
        param.append('userId', localStorage.getItem('xcUserId'));
        param.append('extraPath', '');
        uploadFile(param).then(res => {
          if (res.success) {
            this.isUpload = false;
            getGlobal().then((all) => {
              this.fileSrc = `${all.url}/onlinePreview?fileId=${res.data.id}`;
            });
          } else {
            this.fileSrc = '';
          }
        });

        setTimeout(() => {
          this.previewLoading = false;
        }, 3000);
      }
    },

    handleRemove(file, fileList) {
      this.fileList = [];
      this.isUpload = true;
    },
    showDialogFile() {
      this.fileSrc = '';
      this.fileList = [];
      getUserList({
        userId: localStorage.getItem('xcUserId')
      }).then(res => {
        if (res.success) {
          res.data.map(o => {
            o.id = o.id + '';
          });
          this.fromData = res.data;
        } else {
          this.fromData = [];
        }
      });
      this.dialogVisible = true;
    },
    handelClose() {
      this.$refs.upLoad.clearFiles();
      this.dialogVisible = false;
      this.toData = [];
      this.checked = false;
      this.searchContent = '';
      this.isTips = false;
      setTimeout(() => {
        this.isUpload = true;
      }, 2000);
    },
    goBack() {
      this.transFlag = 1;
    },
    lookTable(row) {
      this.fileSrc = '';
      this.row = {};
      if (row.getWay === 'local') {
        this.row = row;
        getGlobal().then((all) => {
          this.fileSrc = `${all.url}/onlinePreview?fileId=${row.id}`;
        });
        setTimeout(() => {
          this.isLoading = false;
        }, 2500);
      } else {
        this.row.getWay = 'remote';
        this.row.extraPath = row.extraPath;
        this.row.origin_name = row.originName;
        // 文件来自南威的需要特殊处理,后端去处理上传文件，调用接口
        uploadNanWei({
          'extraPath': row.extraPath,
          // 'extraPath': 'http://tw.hebtu.edu.cn/dynamic/download.jsp?id=c92e814856e044fb8080fde63775c74a',
          // 'fileName': '123.doc',
          'fileName': `${row.originName}`,
          'type': 1006
        }).then(res => {
          if (res.success) {
            getGlobal().then((all) => {
              this.fileSrc = `${all.url}/onlinePreview?fileId=${res.data.id}`;
            });
          }
        });
        setTimeout(() => {
          this.isLoading = false;
        }, 3500);
      }

      this.transFlag = 0;
      this.isLoading = true;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getDataSource();
    },
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.getDataSource();
    },
    changePickerValue() {
      this.getDataSource();
    },

    headerCellStyle({ column, columnIndex }) {
      return {
        backgroundColor: 'rgb(64, 158, 255)',
        color: '#fff',
        borderBottom: '1px solid #fff',
        textAlign: 'center'
      };
    },
    getDataSource() {
      this.tableLoading = true;
      getFileList({
        'startTime': this.pickerValue[0],
        'endTime': this.pickerValue[1],
        'fileName': this.filterName,
        'pageSize': this.pageSize,
        'pageIndex': this.pageIndex - 1,
        'type': localStorage.getItem('fileType')
      }).then(res => {
        this.tableLoading = false;
        if (res.success) {
          this.tableData = res.data;
          this.count = res.total;
        } else {
          this.tableData = [];
          this.count = 0;
        }
      });
    },
    searchEvent() {
      this.getDataSource();
    },
    downFile() {
      if (this.row.getWay === 'remote') {
        // 下载到本地
        uploadNanWei({
          'extraPath': this.row.extraPath,
          // 'fileName': '123.doc',
          'fileName': `${this.row.origin_name}`,
          'type': 1005
        }).then(res => {
          if (res.success) {
            getGlobal().then((all) => {
              window.location.href = `${all.url}/file/downloadById?id=${res.data.id}&fileName=${this.row.origin_name}`;
            });
          }
        });
      } else {
        getGlobal().then((all) => {
          window.location.href = `${all.url}/file/downloadById?id=${this.row.id}&fileName=${this.row.originName}`;
        });
      }
    }
  }
};
</script>

<style lang='scss' scoped >
    .fileManagerPage{
      height: 100%;
      padding: 10px;
      position: relative;
    }
    .fileManagerPage_main{
      background: #fff;
      border-radius: 5px;
      height: 100%;
      padding: 5px 15px;
      width: 100%;
      height: 100%;
      background-repeat: no-repeat;
      background-position: center center;
      backface-visibility: hidden;
      transition: 2s;

    }
    .fileManagerPage_main_search{
      margin-top: 15px;
      display: flex;
    }
   .dataPicker /deep/ .el-date-editor .el-range-separator {
    display: inline-block;
    height: 100%;
    padding: 0 5px;
    margin: 0;
    text-align: center;
    line-height: 32px;
    font-size: 14px;
    width: 9% !important;
    color: #303133;
  }
  .fileManagerPage_main_title{
    display: flex;
    margin-top: 20px
  }
  .fileManagerPage_main_title_text{
    flex:6;
    text-align:center;
    width: 96px;
    height: 33px;
    opacity: 1;
    font-size: 22px;
    font-family: PingFangSC, PingFangSC-Medium;
    font-weight: 500;
    text-align: left;
    color: rgba(0,0,0,0.85);
    line-height: 33px;
    text-align: center
  }
  .fileManagerPage_main_table{
    margin-top: 10px
  }
  .fileManagerPage_main_dialog /deep/ .el-dialog {
   margin-top: calc(3vh) !important
}
.deleteSpecial  {
    color: red !important;
}
.commonTable_pagination{
  margin-top: 6px;
  text-align: right
}
.fileManagerPage_main_table /deep/ .vxe-table .vxe-body--row.row--stripe {
    background-color: #e6f7ff;
}
.fileManagerPage_file {
  width: 100%;
  height: 100%;
  transform: rotateY(-180deg);
  position: absolute;
  top:0px;
  left: 0px;
  backface-visibility: hidden;
  transition: 2s;
  padding: 5px 15px;
}
.fileManagerPage_file_main{
  background-color: #fff;
  height: 100%;
}
.fileManagerPage_file_main_title{
  display: flex;
  padding: 10px 20px;
}
.fileManagerPage_file_main_title_text{
  flex:1;
  width: 64px;
  height: 33px;
  opacity: 1;
  font-size: 14px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  text-align: left;
  color: #1890ff;
  line-height: 36px;
}
.fileManagerPage_file_main_title_text:hover{
  cursor: pointer;
  text-decoration: underline
}
.fileManagerPage_file_main_content{
  padding: 5px 20px
}
.filePreviewBg{
   height:calc(74vh);
   width:100%;
   background: url('../../assets/images/filePage/bg.png');
   background-size:100% 100%;
}
.dialogContent{
  display: flex
}
.dialogContent_left{
  flex:1;
  padding:5px
}
.dialogContent_right{
  flex:1.1;
  padding:5px
}
.el-upload__text{
  height: 24px;
  opacity: 1;
  font-size: 16px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  text-align: center;
  color: rgba(0,0,0,0.85);
  line-height: 24px;
}
.dialogContent_left /deep/ .svg-icon {
    width: 4em;
    height: 2em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
    font-size: 1.2rem;
}
.el-upload_type{
  height: 22px;
  opacity: 1;
  font-size: 14px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  text-align: center;
  color: rgba(0,0,0,0.45);
  line-height: 22px;
  margin-top: 5px
}
.dialogContent_right_bg{
   height:100%;
   width:100%;
   background: url('../../assets/images/filePage/bg1.png');
   background-size:100% 100%;
}
.dialogContent_left_treeContainer{
  height: calc(28vh);
  overflow-y: auto;
  padding:5px
}
.dialogContent_left_tips{
  border: 1px solid rgba(0,0,0,0.15);
  border-radius: 3px;
  width: 95%;
}
.dialogContent_left_tips_title{
  display: flex;
  border-bottom: 1px solid rgba(0,0,0,0.15);
  height: 45px;
  line-height: 45px;
  padding: 0px 10px
}
.dialogContent_left_tips_title_right{
  flex:1;
  text-align:right;
  opacity: 1;
  font-size: 14px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  color: rgba(0,0,0,0.65);
}
.dialogContent_left_tips_title_left{
  flex:1;
  opacity: 1;
  font-size: 14px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  color: rgba(0,0,0,0.65);
}
.dialogContent_left /deep/ .el-upload{
  width: 98% !important;
}
.dialogContent_left /deep/  .el-upload-dragger{
  width: 98% !important;
}

</style>
